<script setup lang="ts">
import { ref, onMounted, reactive, getCurrentInstance } from "vue";

const currentIndex = ref(0);

// 获取实例用于导出$el.offsetTop
const tabInstance: any = getCurrentInstance();
// 开发环境使用ctx
// const { ctx }: any = getCurrentInstance();
// 生产环境使用proxy
// const { proxy }: any = getCurrentInstance();

const vDom = reactive({
  vel: {},
});
const tabRef = ref(null);

const props = defineProps({
  titles: {
    type: Array,
    default() {
      return [];
    },
  },
});

const emit = defineEmits(["tabClick"]);

function itemClick(index: number) {
  currentIndex.value = index;
  emit("tabClick", index);
}

// 向父组件导出要暴露的数据，然后父组件通过ref子组件的名字.value.exposeName就能拿到暴露的数据了
defineExpose({
  currentIndex,
  vDom,
});

onMounted(() => {
  vDom.vel = tabInstance.vnode.el;
  // console.log(vDom.vel == tabRef.value);  //true
  // console.log(tabInstance);
  // console.log(tabInstance.vnode.el.offsetTop);
});


</script>

<template>
  <div class="tab-control" ref="tabRef">
    <div
      v-for="(item, index) in titles"
      :key="index"
      class="item"
      :class="{ active: index === currentIndex }"
      @click="itemClick(index)"
    >
      <span>{{ item }}</span>
    </div>
  </div>
</template>

<style lang="css">
.tab-control {
  display: flex;
  text-align: center;
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  background-color: rgb(255, 255, 255);
  z-index: 9;
}

.tab-control .item {
  flex: 1;
}

.tab-control .active {
  color: var(--color-high-text);
}

.tab-control .item span {
  padding: 5px;
}

.tab-control .active span {
  border-bottom: 2px solid var(--color-tint);
}
</style>
